<?php

namespace App\Http\Controllers\Api;

use App\Events\LoanBuyEvent;
use App\Events\LoanTagEvent;
use App\Events\Money\DepositEvent;
use App\Events\Ticket\ConsumeEvent;
use App\Events\Ticket\RefundEvent;
use App\Events\UpdateEvent;
use App\Http\Controllers\Common\Internal;
use App\Models\CityTicket;
use App\Models\LoanApplication;
use App\Models\LoanApplicationLog;
use App\Models\LoanTag;
use App\Models\User;
use App\Models\UserMoneyWithdraw;
use App\Models\UserTakeLog;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Str;


class LoanController extends BaseController
{

    /**
     * 贷款物料列表
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function index(Request $request) {
        $pageSize = (int) $request->input('pageSize', 20);
        $page = (int) $request->input('page', 1);
        $pageSize = min($pageSize, 100); // 分页不能超过一百

        // 没有登录最多能查看2页数据
        if ($page > 2 && !auth('sanctum')->check()) {
            return response()->json([
                'msg' => "查看更多数据，请先登录",
                'code' => 500,
                'data' => [ 'items' => [] ],
            ]);
        }

        $query = LoanApplication::where('is_allocated', 0)->where('user_id', 0)->orderByDesc('apply_at');

        // 类别
        if ($category = $request->category) {
            $loan_type = Internal::getCategoryType($category);
            if(strpos($loan_type,'普通') !== false){
                $query->where('category_type','LIKE',"%综合%");
                if($category == 'has_car'){
                    $query->where('has_car','有');
                }
                if($category == 'has_house'){
                    $query->where('has_house','有');
                }
                if($category == 'has_gongjijin'){
                    $query->where('has_gongjijin','有');
                }
                if($category == 'yingyezhizhao'){
                    $query->where('yingyezhizhao','有');
                }
            }else if($category == 'general'){
                $query->where('category_type','LIKE',"%精准%");
            }else{
                $query->where('category_type', $loan_type);
            }
        }
        if ($province = $request->province) {
            $province = base64_decode($province);
            if (Str::endsWith($province, "省")) {
                $province = Str::replaceLast('省', '', $province);
            }
            if (Str::endsWith($province, "市")) {
                $province = Str::replaceLast('市', '', $province);
            }
            $query->where('province', 'like',  "%{$province}%");
        }



        if ($city = $request->city) {
            $city = base64_decode($city);
            if (Str::endsWith($city, "市")) {
                $city = Str::replaceLast('市', '', $city);
            }
            $query->where('province', 'like', "%{$city}%");
        }

        // 申请金额
        if ($amount_range = $request->amount_range) {
            list($amount_start, $amount_end) = explode('-', $amount_range);
            $query->range(intval($amount_start) * 10000, intval($amount_end) * 10000);
        }

        /* @var $pages \Illuminate\Contracts\Pagination\LengthAwarePaginator */
        $pages = $query->simplePaginate($pageSize);

        $data = [];
        foreach ($pages->items() as $v) {
            $data[] = [
                'id' => $v->id,
                'name' => '客户：实时订单抢单查看',
                'number' => $v->number,
                'amount_start' => $v->amount_start,
                'amount_start_zh' => $v->amount_start_zh,
                'amount_end' => $v->amount_end,
                'amount_end_zh' => $v->amount_end_zh,
                'need_home_service' => $v->need_home_service,
                'province' => Internal::hiddenInfoCity($v->province),
                'city' => '',
                'apply_at' => $v->apply_at,
                'category' => $v->category,
                'need_ticket' => Internal::getNeedTicket($v->category_type, $v->province,$v->id),
                'category_type' => $v->category_type,
                'category_name' => $v->custom_field??$v->category_name,
            ];
        }
        return response()->json([
            'code' => 0,
            'msg' => 'ok',
            'data' => [
                'items' => $data,
            ]
        ]);
    }






    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function detail(Request $request, $id)
    {
        $loan = LoanApplication::with(['creditProvident', 'mortgageCar', 'mortgageHouse', 'mortgageTax'])
            ->where('is_allocated', 0)->where('user_id', 0)->find($id);
        if (empty($loan)) {
            return response()->json([
                'code' => 1,
                'msg' => '没有数据权限',
                'data' => null
            ]);
        } else {



            $zhima = "无";
            if($loan->zhima == 2){
                $zhima = '600分以下';
            }elseif ($loan->zhima == 3){
                $zhima = '600-650分';
            }elseif ($loan->zhima == 4){
                $zhima = '650-700分';
            }elseif ($loan->zhima == 5){
                $zhima = '大于700';
            }
            return response()->json([
                'code' => 0,
                'msg' => 'ok',
                'data' => [
                    'status'=> $loan->user_id>0?1:0,
                    'id' => $loan->id,
                    'name' => '客户：实时订单抢单查看',
                    'number' => $loan->number,
                    'amount_start' => $loan->amount_start,
                    'amount_start_zh' => $loan->amount_start_zh,
                    'amount_end' => $loan->amount_end,
                    'amount_end_zh' => $loan->amount_end_zh,
                    'need_home_service' => $loan->need_home_service,
                    'province' => $loan->province,
                    'channel_name' => $loan->channel_name,
                    'city' => $loan->city,
                    'need_ticket' => Internal::getNeedTicket($loan->category_type, $loan->province,$loan->id),
                    'has_house'=>Internal::getDataPQ($loan->has_house),
                    'has_car'=>Internal::getDataPQ($loan->has_car),
                    'has'=>Internal::getDataPQ($loan->has),
                    'yingyezhizhao'=>Internal::getDataPQ($loan->yingyezhizhao),
                    'has_gongjijin'=>Internal::getDataPQ($loan->has_gongjijin),
                    'zhima'=>$zhima,
                    'apply_at' => $loan->apply_at,
                    'category' => $loan->category,
                    'category_name' => $loan->custom_field??$loan->category_name,
                    'category_type' => $loan->category_type,
                    'profile' => [
                        'company_name' => $loan->creditProvident ?  Internal::getDataPQ($loan->creditProvident->company_name) : '-',
                        'pay_method' => $loan->creditProvident ?  Internal::getDataPQ($loan->creditProvident->pay_method) : '-',
                        'month_salary' => $loan->creditProvident ?  Internal::getDataPQ($loan->creditProvident->month_salary) : '-',
                        'provident_age' => $loan->creditProvident ?  Internal::getDataPQ($loan->creditProvident->provident_age) : '-',
                        'month_provident' => $loan->creditProvident ?  Internal::getDataPQ($loan->creditProvident->month_provident) : '-',
//                        'pay_method' => '-',
//                        'education' => '-',
//                        'salary' => $loan->creditProvident  && $loan->creditProvident->annal_turnover > 0  ?  toZhNum($loan->creditProvident->month_salary) : '-',
//                        'social_insurance_age' => $loan->creditProvident ?  $loan->creditProvident->social_insurance_age : '-',
                    ],
                    'house' => [
                        'type' => $loan->mortgageHouse ?  Internal::getDataPQ($loan->mortgageHouse->type) : '-',
                        'has_certificate' => $loan->mortgageHouse ?  Internal::getDataPQ($loan->mortgageHouse->has_certificate) : '-',
                        'latest_estimated' => $loan->mortgageHouse ?  Internal::getDataPQ($loan->mortgageHouse->latest_estimated) : '-',
//                        'has_certificate' => $loan->mortgageHouse ?  ($loan->mortgageHouse->has_certificate ? '是' : '否') : '-',
//                        'ownership' => $loan->mortgageHouse ?  ($loan->mortgageHouse->ownership ? '是' : '否') : '-',
//                        'latest_estimated' => $loan->mortgageHouse && $loan->mortgageHouse->latest_estimated > 0 ?  toZhNum($loan->mortgageHouse->latest_estimated) : '-',
                    ],
                    'car' => [
                        'info' => ($loan->mortgageCar && $loan->mortgageCar->info) ?  Internal::getDataPQ($loan->mortgageCar->info) : '-',
                        'car_model' => ($loan->mortgageCar && $loan->mortgageCar->car_model) ?  Internal::getDataPQ($loan->mortgageCar->car_model) : '-',
                        'car_price_estimation' => ($loan->mortgageCar && $loan->mortgageCar->car_price_estimation) ?  Internal::getDataPQ($loan->mortgageCar->car_price_estimation) : '-',
                    ],
                    'company' => [
                        'company_name' => $loan->mortgageTax ?  Internal::getDataPQ($loan->mortgageTax->company_name) : '-',
                        'annal_tax' => $loan->mortgageTax ?  Internal::getDataPQ($loan->mortgageTax->annal_tax) : '-',
                        'annal_turnover' => $loan->mortgageTax ?  Internal::getDataPQ($loan->mortgageTax->annal_turnover) : '-',
                        'company_age' => $loan->mortgageTax ?  Internal::getDataPQ($loan->mortgageTax->company_age) : '-',
                        'is_legal_person' => $loan->mortgageTax ?  Internal::getDataPQ($loan->mortgageTax->is_legal_person) : '-',
                    ],
                ]
            ]);
        }
    }

    public function getHiddenName($str)
    {
        $length = mb_strlen($str); // 获取字符串长度（按字符计算）

        if ($length > 1) {
            $firstChar = mb_substr($str, 0, 1); // 获取第一个字符
            $maskedStr = $firstChar . str_repeat('*', $length - 1); // 除第一个字符外，其它用*号代替
        } else {
            $maskedStr = $str; // 如果只有一个字符，直接使用原字符串
        }
        return $maskedStr;
    }


    /**
     * 抢单
     *
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function take(Request $request, $id)
    {
        // 必须实名认证
        $user = $request->user();
        if ($user->kyc != 2) {
            return response()->json([
                'code' => 1,
                'msg' => '请先完成实名认证',
                'data' => null
            ]);
        }

        if ($user->status != 1) {
            return response()->json([
                'code' => 403,
                'msg' => '当前用户状态不能操作'
            ], 403);
        }

        // 普通用户每天最多抢1单
        if (empty($user->org_code)) {
            $cnt = UserTakeLog::where('user_id', $user->id)
            ->whereBetween('created_at', [date("Y-m-d 00:00:00"), date("Y-m-d 23:59:59")])
                ->count();
            if ($cnt >= 1) {
                return response()->json([
                    'code' => 1,
                    'msg' => '每日抢单限额1次, 请联系客服进行升级',
                    'data' => null
                ]);
            }
        }

        $loan = LoanApplication::where('is_allocated', 0)->where('user_id', 0)->find($id);
        if (empty($loan)) {
            return response()->json([
                'code' => 1,
                'msg' => '手速慢了，已被抢掉',
                'data' => null
            ]);
        }

        $price_ticket = Internal::getNeedTicket($loan->category_type, $loan->province,$loan->id);


        if ($user->ticket < $price_ticket) {
            return response()->json([
                'code' => 1,
                'msg' => '抢单次数余额不足',
                'data' => null
            ]);
        }

        $loan->user_id = $user->id;
        $loan->is_allocated = 0;
        if (!empty($user->org_code)) {
            $loan->org_code = $user->org_code;
        }

        $user->ticket -= $price_ticket;

        if ($user->save() && $loan->save()) {
            UserTakeLog::create([
                'user_id' => $user->id,
                'loan_id' => $loan->id,
                'price_ticket' => $price_ticket
            ]);

            LoanBuyEvent::dispatch($loan, $user);

            ConsumeEvent::dispatch($user->id, -$price_ticket);
            return response()->json([
                'code' => 0,
                'msg' => '抢单成功',
                'data' => null
            ]);
        } else {
            return response()->json([
                'code' => 1,
                'msg' => '抢单失败',
                'data' => null
            ]);
        }
    }

    public function tag(Request $request, $id) {
        $user = $request->user();
        $loan = LoanApplication::ofOwner($user)->find($id);
        if (empty($loan)) {
            return response()->json([
                'code' => 1,
                'msg' => '没有数据权限',
                'data' => null
            ]);
        }

        $res = [];
        foreach ($loan->tags as $v) {
            $res[] = [
                'id' => $v->id,
                'title' => $v->title,
            ];
        }

        return response()->json([
            'code' => 0,
            'msg' => 'ok',
            'data' => $res
        ]);
    }

    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse|void
     */
    public function saveTag(Request $request, $id)
    {
        $user = $request->user();
        $loan = LoanApplication::ofOwner($user)->find($id);
        if (empty($loan)) {
            return response()->json([
                'code' => 1,
                'msg' => '没有数据权限',
                'data' => null
            ]);
        }

        if (empty($request->tags)) {
            $detached = [];
            foreach ($loan->tags as $v) {
                $detached[] = $v->id;
            }
            $loan->tags()->detach();

            LoanTagEvent::dispatch($loan, $user, [], $detached);
            return response()->json([
                'code' => 0,
                'msg' => 'ok',
                'data' => null
            ]);
        }

        $tag_ids = [];
        foreach ($request->tags as $v) {
            $tag =  LoanTag::ofOwner($user)->find($v['id']);
            if (empty($tag)) {
                return response()->json([
                    'code' => 1,
                    'msg' => sprintf("没有标签权限: [%s]", $v['title']),
                    'data' => null
                ]);
            }

            $tag_ids[] = (int) $v['id'];
        }

        $changes = $loan->tags()->sync($tag_ids);

        LoanTagEvent::dispatch($loan, $user, $changes['attached'], $changes['detached']);

        return response()->json([
            'code' => 0,
            'msg' => 'ok',
            'data' => null
        ]);
    }


    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse|void
     */
    public function comment(Request $request, $id) {
        $pageSize = (int) $request->input('pageSize', 20);
        $loan = LoanApplication::ofOwner($request->user())->find($id);
        if (empty($loan)) {
            return response()->json([
                'code' => 1,
                'msg' => '没有数据权限',
                'data' => null
            ]);
        }
        /* @var $pages \Illuminate\Contracts\Pagination\LengthAwarePaginator */
        $pages = LoanApplicationLog::with("user")
            ->where('loan_id', $id)
            ->orderByDesc('id')->paginate($pageSize);

        $logs = [];
        foreach ($pages->items() as $v) {
            $logs[] = [
                'user_name' => $v->user->name,
                'comment' => $v->comment,
                'created_at' => $v->created_at->format('Y/m/d H:i'),
            ];
        }

        return response()->json([
            'code' => 0,
            'msg' => 'ok',
            'data' => [
                'items' => $logs
            ]
        ]);
    }

    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function saveComment(Request $request, $id)
    {
        $loan = LoanApplication::ofOwner($request->user())->find($id);
        if (empty($loan)) {
            return response()->json([
                'code' => 1,
                'msg' => '没有数据权限',
                'data' => null
            ]);
        }

        if(empty(trim($request->comment))) {
            return response()->json([
                'code' => 1,
                'msg' => '内容不能为空',
                'data' => null
            ]);
        }

        $loanLog = new LoanApplicationLog();
        $loanLog->comment = trim($request->comment);
        $loanLog->loan_id = $loan->id;
        $loanLog->user_id = $request->user()->id;
        $loanLog->org_root = $request->user()->org_root;
        $loanLog->org_code = $request->user()->org_code;

        if($loanLog->save()) {
            $loanLog->load('user');
            return response()->json([
                'code' => 0,
                'msg' => '保存成功',
                'data' =>  [
                    'user_name' => $loanLog->user->name,
                    'comment' => $loanLog->comment,
                    'created_at' => $loanLog->created_at->format('Y/m/d H:i'),
                ]
            ]);
        } else {
            return response()->json([
                'code' => 1,
                'msg' => '保存失败',
                'data' => null
            ]);
        }
    }



    public function saveStatus(Request $request, $id) {

        $loan = LoanApplication::ofOwner($request->user())->find($id);
        if (empty($loan)) {
            return response()->json([
                'code' => 1,
                'msg' => '没有数据权限',
                'data' => null
            ]);
        }
        $origin = $loan->toArray();

        $loan->status = (int) $request->status;
        if($loan->save()) {
            UpdateEvent::dispatch($origin, $loan->toArray(), $request->user());
            return response()->json([
                'code' => 0,
                'msg' => '更新成功',
                'data' => $loan
            ]);
        } else {
            return response()->json([
                'code' => 1,
                'msg' => '更新失败',
                'data' => null
            ]);
        }
    }
}
